"use client"

import React, { useState } from "react"
import { Box, Typography, Button, Paper, IconButton, Tooltip, Collapse, Link, Divider, List, ListItem, ListItemText } from "@mui/material"
import { Visibility as PreviewIcon, Code as CodeIcon, ContentCopy as CopyIcon } from "@mui/icons-material"
import ReactMarkdown from "react-markdown"
import remarkGfm from "remark-gfm"
import rehypeHighlight from "rehype-highlight"
import useAppStore from "@/store/useAppStore"

interface MarkdownMessageProps {
	content: string
}

export default function MarkdownMessage({ content }: MarkdownMessageProps) {
	const [copied, setCopied] = useState(false)
	const { setSidebarContent } = useAppStore()

	// 复制代码到剪贴板
	const copyToClipboard = async (code: string) => {
		try {
			await navigator.clipboard.writeText(code)
			setCopied(true)
			setTimeout(() => setCopied(false), 2000)
		} catch (err) {
			console.error("复制失败:", err)
		}
	}

	// 在侧栏中预览HTML
	const previewInSidebar = (htmlCode: string) => {
		setSidebarContent(htmlCode, "HTML 预览")
	}

	// 自定义Markdown组件渲染器
	const components = {
		// 标题样式 - 响应式设计
		h1: ({ children }: any) => (
			<Typography
				variant='h4'
				component='h1'
				sx={{
					fontWeight: 600,
					mb: { xs: 1.5, sm: 2 },
					mt: { xs: 2, sm: 3 },
					color: "primary.main",
					fontSize: { xs: "1.5rem", sm: "2rem" }
				}}
			>
				{children}
			</Typography>
		),
		h2: ({ children }: any) => (
			<Typography
				variant='h5'
				component='h2'
				sx={{
					fontWeight: 600,
					mb: { xs: 1, sm: 1.5 },
					mt: { xs: 1.5, sm: 2.5 },
					color: "primary.main",
					fontSize: { xs: "1.25rem", sm: "1.5rem" }
				}}
			>
				{children}
			</Typography>
		),
		h3: ({ children }: any) => (
			<Typography
				variant='h6'
				component='h3'
				sx={{
					fontWeight: 600,
					mb: { xs: 0.75, sm: 1 },
					mt: { xs: 1.25, sm: 2 },
					color: "text.primary",
					fontSize: { xs: "1.1rem", sm: "1.25rem" }
				}}
			>
				{children}
			</Typography>
		),
		h4: ({ children }: any) => (
			<Typography
				variant='subtitle1'
				component='h4'
				sx={{
					fontWeight: 600,
					mb: { xs: 0.5, sm: 1 },
					mt: { xs: 1, sm: 1.5 },
					color: "text.primary",
					fontSize: { xs: "1rem", sm: "1.1rem" }
				}}
			>
				{children}
			</Typography>
		),
		h5: ({ children }: any) => (
			<Typography
				variant='subtitle2'
				component='h5'
				sx={{
					fontWeight: 600,
					mb: { xs: 0.25, sm: 0.5 },
					mt: { xs: 0.75, sm: 1 },
					color: "text.primary",
					fontSize: { xs: "0.95rem", sm: "1rem" }
				}}
			>
				{children}
			</Typography>
		),
		h6: ({ children }: any) => (
			<Typography
				variant='body1'
				component='h6'
				sx={{
					fontWeight: 600,
					mb: { xs: 0.25, sm: 0.5 },
					mt: { xs: 0.5, sm: 1 },
					color: "text.secondary",
					fontSize: { xs: "0.9rem", sm: "0.95rem" }
				}}
			>
				{children}
			</Typography>
		),

		// 段落样式 - 响应式设计
		p: ({ children }: any) => (
			<Typography
				variant='body1'
				sx={{
					mb: { xs: 1, sm: 1.5 },
					lineHeight: 1.7,
					wordBreak: "break-word",
					fontSize: { xs: "0.95rem", sm: "1rem" }
				}}
			>
				{children}
			</Typography>
		),

		// 链接样式 - 移动端优化
		a: ({ href, children }: any) => (
			<Link
				href={href}
				target='_blank'
				rel='noopener noreferrer'
				sx={{
					color: "primary.main",
					textDecoration: "underline",
					fontSize: { xs: "0.95rem", sm: "1rem" },
					"&:hover": {
						textDecoration: "none",
						opacity: 0.8
					}
				}}
			>
				{children}
			</Link>
		),

		// 列表样式 - 响应式设计
		ul: ({ children }: any) => <List sx={{ pl: { xs: 1.5, sm: 2 }, mb: { xs: 1, sm: 1.5 } }}>{children}</List>,
		ol: ({ children }: any) => (
			<List component='ol' sx={{ pl: { xs: 1.5, sm: 2 }, mb: { xs: 1, sm: 1.5 } }}>
				{children}
			</List>
		),
		li: ({ children }: any) => (
			<ListItem sx={{ py: { xs: 0.125, sm: 0.25 }, px: 0 }}>
				<ListItemText
					primary={children}
					sx={{
						"& .MuiListItemText-primary": {
							fontSize: { xs: "0.9rem", sm: "0.95rem" },
							lineHeight: 1.6
						}
					}}
				/>
			</ListItem>
		),

		// 代码块样式
		code({ node, inline, className, children, ...props }: any) {
			const match = /language-(\w+)/.exec(className || "")
			const language = match ? match[1] : ""

			// 递归提取所有文本内容的函数
			const extractTextContent = (element: any): string => {
				if (typeof element === "string") {
					return element
				}
				if (typeof element === "number") {
					return String(element)
				}
				if (Array.isArray(element)) {
					return element.map(extractTextContent).join("")
				}
				if (element && typeof element === "object") {
					if (element.props && element.props.children) {
						return extractTextContent(element.props.children)
					}
					if (element.children) {
						return extractTextContent(element.children)
					}
				}
				return ""
			}

			// 提取代码文本内容
			const codeText = extractTextContent(children)

			// HTML代码块特殊处理
			if (!inline && language === "html") {
				return (
					<Paper
						elevation={1}
						sx={{
							p: 2,
							bgcolor: "grey.50",
							border: "1px solid",
							borderColor: "grey.200",
							borderRadius: 2,
							my: 2
						}}
					>
						<Box
							sx={{
								display: "flex",
								alignItems: "center",
								justifyContent: "space-between",
								mb: 1,
								pb: 1,
								borderBottom: "1px solid",
								borderColor: "grey.200"
							}}
						>
							<Box sx={{ display: "flex", alignItems: "center", gap: 1 }}>
								<CodeIcon fontSize='small' color='primary' />
								<Typography variant='caption' color='text.secondary'>
									HTML 代码
								</Typography>
							</Box>
							<Box sx={{ display: "flex", gap: 0.5 }}>
								<Tooltip title={copied ? "已复制" : "复制代码"}>
									<IconButton size='small' onClick={() => copyToClipboard(codeText)} sx={{ p: 0.5 }}>
										<CopyIcon fontSize='small' />
									</IconButton>
								</Tooltip>
								<Tooltip title='在侧栏预览HTML'>
									<IconButton size='small' onClick={() => previewInSidebar(codeText)} sx={{ p: 0.5 }}>
										<PreviewIcon fontSize='small' />
									</IconButton>
								</Tooltip>
							</Box>
						</Box>
						<Box
							sx={{
								fontFamily: 'Monaco, Menlo, "Ubuntu Mono", monospace',
								fontSize: "0.85rem",
								lineHeight: 1.4,
								color: "text.primary",
								whiteSpace: "pre-wrap",
								wordBreak: "break-word",
								overflow: "auto",
								maxHeight: "300px",
								p: 1,
								bgcolor: "background.paper",
								borderRadius: 1,
								border: "1px solid",
								borderColor: "grey.300"
							}}
						>
							{children}
						</Box>
					</Paper>
				)
			}

			// 普通代码块
			if (!inline) {
				return (
					<Paper
						elevation={0}
						sx={{
							p: { xs: 1.5, sm: 2 },
							bgcolor: "grey.100",
							border: "1px solid",
							borderColor: "grey.300",
							borderRadius: 2,
							my: { xs: 1, sm: 1.5 },
							overflow: "auto"
						}}
					>
						<Box
							component='pre'
							sx={{
								fontFamily: 'Monaco, Menlo, "Ubuntu Mono", monospace',
								fontSize: { xs: "0.75rem", sm: "0.85rem" },
								lineHeight: 1.4,
								color: "text.primary",
								whiteSpace: "pre-wrap",
								wordBreak: "break-word",
								margin: 0
							}}
							{...props}
						>
							{children}
						</Box>
					</Paper>
				)
			}

			// 真正的行内代码样式
			// return (
			// 	<code
			// 		style={{
			// 			fontFamily: 'Menlo, Monaco, "Courier New", monospace',
			// 			fontSize: "0.85em",
			// 			backgroundColor: "#f5f5f5",
			// 			color: "#d73a49",
			// 			padding: "0.2em 0.4em",
			// 			margin: "0",
			// 			borderRadius: "4px",
			// 			border: "1px solid #e1e4e8",
			// 			display: "inline", // 确保是行内显示
			// 			whiteSpace: "nowrap" // 防止换行
			// 		}}
			// 		{...props}
			// 	>
			// 		{children}
			// 	</code>
			// )
		},

		// 引用块样式 - 响应式设计
		blockquote: ({ children }: any) => (
			<Paper
				elevation={0}
				sx={{
					borderLeft: 4,
					borderColor: "primary.main",
					bgcolor: "primary.50",
					p: { xs: 1.5, sm: 2 },
					my: { xs: 1, sm: 1.5 },
					borderRadius: 0
				}}
			>
				<Typography
					variant='body1'
					sx={{
						fontStyle: "italic",
						color: "text.secondary",
						fontSize: { xs: "0.9rem", sm: "1rem" }
					}}
				>
					{children}
				</Typography>
			</Paper>
		),

		// 分割线样式 - 响应式设计
		hr: () => <Divider sx={{ my: { xs: 1.5, sm: 2 } }} />,

		// 表格样式 - 响应式设计
		table: ({ children }: any) => (
			<Box sx={{ overflow: "auto", my: { xs: 1.5, sm: 2 }, maxWidth: "100%" }}>
				<Box
					component='table'
					sx={{
						minWidth: { xs: 250, sm: 300 },
						borderCollapse: "collapse",
						width: "100%",
						fontSize: { xs: "0.85rem", sm: "0.9rem" }
					}}
				>
					{children}
				</Box>
			</Box>
		),
		thead: ({ children }: any) => (
			<Box component='thead' sx={{ bgcolor: "grey.100" }}>
				{children}
			</Box>
		),
		tbody: ({ children }: any) => <Box component='tbody'>{children}</Box>,
		tr: ({ children }: any) => (
			<Box component='tr' sx={{ borderBottom: "1px solid", borderColor: "grey.300" }}>
				{children}
			</Box>
		),
		th: ({ children }: any) => (
			<Box
				component='th'
				sx={{
					p: { xs: 0.75, sm: 1 },
					textAlign: "left",
					fontWeight: 600,
					borderRight: "1px solid",
					borderColor: "grey.300",
					fontSize: { xs: "0.8rem", sm: "0.85rem" }
				}}
			>
				{children}
			</Box>
		),
		td: ({ children }: any) => (
			<Box
				component='td'
				sx={{
					p: { xs: 0.75, sm: 1 },
					borderRight: "1px solid",
					borderColor: "grey.300",
					fontSize: { xs: "0.8rem", sm: "0.85rem" }
				}}
			>
				{children}
			</Box>
		)
	}

	return (
		<Box sx={{ "& > *:first-of-type": { mt: 0 }, "& > *:last-child": { mb: 0 } }}>
			<ReactMarkdown remarkPlugins={[remarkGfm]} rehypePlugins={[rehypeHighlight]} components={components}>
				{content}
			</ReactMarkdown>
		</Box>
	)
}
